<script setup lang="ts">
import { onMounted, ref } from "vue";
import { Dropdown, Menu, MenuItem } from "ant-design-vue";
import { Service, UserInfoOutput } from "../api";
import LoginModal from "./LoginModal.vue";
import RegisterModal from "./RegisterModal.vue";
import { useStore } from "../stores/";
const store = useStore();
const loadUserInfo = async () => {
  try {
    const token = localStorage.getItem("token");
    if (token) {
      const userInfo = await Service.getUserInfo();
      store.setUserInfo(userInfo);
    }
  } catch (error) {
    console.error(error);
  }
};

const loginModalOpen = ref<boolean>(false);
const toLogin = () => {
  loginModalOpen.value = true;
  registerModalOpen.value = false;
};
const loginFinish = (u: UserInfoOutput) => {
  loginModalOpen.value = false;
  store.setUserInfo(u);
};

const registerModalOpen = ref<boolean>(false);
const toReigister = () => {
  loginModalOpen.value = false;
  registerModalOpen.value = true;
};

const logout = () => {
  localStorage.removeItem("token");
  store.clear();
};
onMounted(() => {
  if (store.userInfo == undefined) {
    loadUserInfo();
  }
});
</script>
<template>
  <div style="text-align: right; font-size: 16px; color: #eee">
    <Dropdown v-if="store.userInfo">
      <span>欢迎, {{ store.userInfo.name }} </span>
      <template #overlay>
        <Menu>
          <MenuItem key="1" @click="logout">退出登录</MenuItem>
        </Menu>
      </template>
    </Dropdown>

    <a v-else @click="toLogin">请登录</a>
  </div>
  <LoginModal
    v-model:open="loginModalOpen"
    @to-reigister="toReigister"
    @finish="loginFinish"
  ></LoginModal>
  <RegisterModal
    v-model:open="registerModalOpen"
    @to-login="toLogin"
    @finish="toLogin"
  ></RegisterModal>
</template>
<style scoped></style>
